package com.tanhua.server.interceptor;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.common.utils.Cache;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class RedisCacheInterceptor implements HandlerInterceptor {
    @Value("${tanhua.cache.enable}")
    private boolean enable;
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    private  static final ObjectMapper MAPPER=new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       if(enable==false)
           return true;
       if(!(handler instanceof HandlerMethod))
       {
            return true;
       }
       if(!(((HandlerMethod) handler).hasMethodAnnotation(GetMapping.class)))
       {
           return true;
       }
        if(!(((HandlerMethod) handler).hasMethodAnnotation(Cache.class)))
        {
            return true;
        }
        String rediskey=createRediskey(request);
        String cacheData = redisTemplate.opsForValue().get(rediskey);
        if(StringUtils.isEmpty(cacheData))
            return true;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(cacheData);

        return false;
    }



    public static String createRediskey(HttpServletRequest httpRequest) throws JsonProcessingException {
        String requestURI = httpRequest.getRequestURI();
        String s = MAPPER.writeValueAsString(httpRequest.getParameterMap());
        String token=httpRequest.getHeader("Authorization");
        String data=requestURI+"_"+s+"_"+token;
        return "SERVER_CACHE_DATA_" + DigestUtils.md5Hex(data);
    }
}
